import 'package:path_provider/path_provider.dart';
import 'dart:io';

class CacheUtils {

  // 获取缓存目录
  static Future<String> getCacheDirectory() async {
    Directory cacheDir = await getTemporaryDirectory();
    return cacheDir.path;
  }

  // 获取缓存文件大小
  static Future<int> getCacheFileSize() async {
    String cacheDirPath = await getCacheDirectory();
    int totalSize = 0;

    Directory cacheDir = Directory(cacheDirPath);
    if (cacheDir.existsSync()) {
      List<FileSystemEntity> files = cacheDir.listSync(recursive: true);
      for (FileSystemEntity file in files) {
        if (file is File) {
          totalSize += await file.length();
        }
      }
    }

    return totalSize;
  }

  // 清除缓存
  static Future<void> clearCache() async {
    String cacheDirPath = await getCacheDirectory();

    Directory cacheDir = Directory(cacheDirPath);
    if (cacheDir.existsSync()) {
      await cacheDir.delete(recursive: true);
    }
  }

  static String formatFileSize(int fileSize) {
    if (fileSize < 1024) {
      return '${fileSize.toStringAsFixed(2)} B';
    } else if (fileSize < 1024 * 1024) {
      double kbSize = fileSize / 1024;
      return  '${kbSize.toStringAsFixed(2)} KB';
    } else if (fileSize < 1024 * 1024 * 1024) {
      double mbSize = fileSize / (1024 * 1024);
      return '${mbSize.toStringAsFixed(2)} MB';
    } else {
      double gbSize = fileSize / (1024 * 1024 * 1024);
      return '${gbSize.toStringAsFixed(2)} GB';
    }
  }

}